"""
钱包相关接口
"""
from fastapi import APIRouter, Depends, HTTPException, status as http_status, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc
from app.core.dependencies import get_db, get_current_user
from app.models.user import User
from app.models.wallet import Wallet, Transaction, TransactionType, TransactionStatus
from app.schemas.wallet import (
    WalletResponse, TransactionResponse, RechargeRequest,
    WithdrawRequest, TransferRequest, TransactionFilterParams
)
from app.schemas.common import ApiResponse, PageData
from app.utils.helpers import generate_id
from datetime import datetime
from typing import Optional
from loguru import logger

router = APIRouter()


def get_or_create_wallet(db: Session, user_id: str) -> Wallet:
    """获取或创建钱包"""
    wallet = db.query(Wallet).filter(Wallet.user_id == user_id).first()
    if not wallet:
        wallet = Wallet(
            id=generate_id(),
            user_id=user_id,
            balance=0.0,
            frozen_amount=0.0
        )
        db.add(wallet)
        db.commit()
        db.refresh(wallet)
        logger.info(f" 创建钱包: user_id={user_id}, wallet_id={wallet.id}")
    return wallet


@router.get("/info", response_model=ApiResponse[WalletResponse])
async def get_wallet_info(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取钱包信息"""
    wallet = get_or_create_wallet(db, current_user.id)
    return ApiResponse(data=WalletResponse(**wallet.to_dict()))


@router.post("/recharge", response_model=ApiResponse[TransactionResponse])
async def recharge_wallet(
    request: RechargeRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    充值
    TODO: 集成微信支付/支付宝
    """
    wallet = get_or_create_wallet(db, current_user.id)
    
    # 创建充值交易记录
    transaction = Transaction(
        id=generate_id(),
        wallet_id=wallet.id,
        user_id=current_user.id,
        type=TransactionType.RECHARGE,
        amount=request.amount,
        balance_before=wallet.balance,
        balance_after=wallet.balance + request.amount,
        status=TransactionStatus.PENDING,
        description=f"充值 ¥{request.amount}",
        payment_method=request.paymentMethod
    )
    
    # TODO: 调用支付接口
    # 这里模拟支付成功
    transaction.status = TransactionStatus.SUCCESS
    transaction.completed_at = datetime.now()
    
    # 更新钱包余额
    wallet.balance += request.amount
    wallet.total_recharge += request.amount
    wallet.updated_at = datetime.now()
    
    db.add(transaction)
    db.commit()
    db.refresh(transaction)
    
    logger.info(f"💰 充值成功: user_id={current_user.id}, amount={request.amount}")
    
    return ApiResponse(
        message="充值成功",
        data=TransactionResponse(**transaction.to_dict())
    )


@router.post("/withdraw", response_model=ApiResponse[TransactionResponse])
async def withdraw_wallet(
    request: WithdrawRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    提现
    TODO: 集成提现到银行卡/微信/支付宝
    """
    wallet = get_or_create_wallet(db, current_user.id)
    
    # 检查余额
    if wallet.balance < request.amount:
        raise HTTPException(
            status_code=http_status.HTTP_400_BAD_REQUEST,
            detail=f"余额不足。当前余额: ¥{wallet.balance}"
        )
    
    # 检查最低提现金额
    min_withdraw = 10.0
    if request.amount < min_withdraw:
        raise HTTPException(
            status_code=http_status.HTTP_400_BAD_REQUEST,
            detail=f"单笔提现金额不能少于 ¥{min_withdraw}"
        )
    
    # 创建提现交易记录
    transaction = Transaction(
        id=generate_id(),
        wallet_id=wallet.id,
        user_id=current_user.id,
        type=TransactionType.WITHDRAW,
        amount=request.amount,
        balance_before=wallet.balance,
        balance_after=wallet.balance - request.amount,
        status=TransactionStatus.PENDING,
        description=f"提现 ¥{request.amount}",
        remark=f"银行卡: {request.bankAccount}"
    )
    
    # TODO: 调用提现接口
    # 这里模拟提现申请提交
    
    # 冻结金额（提现审核中）
    wallet.frozen_amount += request.amount
    wallet.balance -= request.amount
    wallet.updated_at = datetime.now()
    
    db.add(transaction)
    db.commit()
    db.refresh(transaction)
    
    logger.info(f"💸 提现申请: user_id={current_user.id}, amount={request.amount}")
    
    return ApiResponse(
        message="提现申请已提交，预计1-3个工作日到账",
        data=TransactionResponse(**transaction.to_dict())
    )


@router.post("/transfer", response_model=ApiResponse[TransactionResponse])
async def transfer_wallet(
    request: TransferRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """转账给其他用户"""
    # 检查是否转账给自己
    if request.toUserId == current_user.id:
        raise HTTPException(
            status_code=http_status.HTTP_400_BAD_REQUEST,
            detail="不能转账给自己"
        )
    
    # 检查接收方用户是否存在
    to_user = db.query(User).filter(User.id == request.toUserId).first()
    if not to_user:
        raise HTTPException(
            status_code=http_status.HTTP_404_NOT_FOUND,
            detail="接收方用户不存在"
        )
    
    # 获取或创建钱包
    from_wallet = get_or_create_wallet(db, current_user.id)
    to_wallet = get_or_create_wallet(db, request.toUserId)
    
    # 检查余额
    if from_wallet.balance < request.amount:
        raise HTTPException(
            status_code=http_status.HTTP_400_BAD_REQUEST,
            detail=f"余额不足。当前余额: ¥{from_wallet.balance}"
        )
    
    # 创建转出交易记录
    transfer_out = Transaction(
        id=generate_id(),
        wallet_id=from_wallet.id,
        user_id=current_user.id,
        type=TransactionType.TRANSFER_OUT,
        amount=request.amount,
        balance_before=from_wallet.balance,
        balance_after=from_wallet.balance - request.amount,
        status=TransactionStatus.SUCCESS,
        description=f"转账给 {to_user.nick_name}",
        related_id=request.toUserId,
        related_type="user",
        remark=request.remark,
        completed_at=datetime.now()
    )
    
    # 创建转入交易记录
    transfer_in = Transaction(
        id=generate_id(),
        wallet_id=to_wallet.id,
        user_id=request.toUserId,
        type=TransactionType.TRANSFER_IN,
        amount=request.amount,
        balance_before=to_wallet.balance,
        balance_after=to_wallet.balance + request.amount,
        status=TransactionStatus.SUCCESS,
        description=f"收到来自 {current_user.nick_name} 的转账",
        related_id=current_user.id,
        related_type="user",
        remark=request.remark,
        completed_at=datetime.now()
    )
    
    # 更新钱包余额
    from_wallet.balance -= request.amount
    from_wallet.updated_at = datetime.now()
    
    to_wallet.balance += request.amount
    to_wallet.updated_at = datetime.now()
    
    db.add(transfer_out)
    db.add(transfer_in)
    db.commit()
    db.refresh(transfer_out)
    
    logger.info(f"💸 转账成功: from={current_user.id}, to={request.toUserId}, amount={request.amount}")
    
    return ApiResponse(
        message="转账成功",
        data=TransactionResponse(**transfer_out.to_dict())
    )


@router.get("/transactions", response_model=ApiResponse[PageData[TransactionResponse]])
async def get_transactions(
    type: Optional[TransactionType] = Query(None, description="交易类型"),
    status: Optional[TransactionStatus] = Query(None, description="交易状态"),
    startDate: Optional[str] = Query(None, description="开始日期"),
    endDate: Optional[str] = Query(None, description="结束日期"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取交易记录"""
    # 构建查询条件
    conditions = [Transaction.user_id == current_user.id]
    
    if type:
        conditions.append(Transaction.type == type)
    
    if status:
        conditions.append(Transaction.status == status)
    
    if startDate:
        try:
            start = datetime.fromisoformat(startDate)
            conditions.append(Transaction.created_at >= start)
        except ValueError:
            raise HTTPException(
                status_code=http_status.HTTP_400_BAD_REQUEST,
                detail="开始日期格式错误"
            )
    
    if endDate:
        try:
            end = datetime.fromisoformat(endDate + " 23:59:59")
            conditions.append(Transaction.created_at <= end)
        except ValueError:
            raise HTTPException(
                status_code=http_status.HTTP_400_BAD_REQUEST,
                detail="结束日期格式错误"
            )
    
    # 查询总数
    total = db.query(Transaction).filter(and_(*conditions)).count()
    
    # 查询数据
    transactions = (
        db.query(Transaction)
        .filter(and_(*conditions))
        .order_by(desc(Transaction.created_at))
        .offset((page - 1) * pageSize)
        .limit(pageSize)
        .all()
    )
    
    return ApiResponse(
        data=PageData(
            list=[TransactionResponse(**t.to_dict()) for t in transactions],
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/balance", response_model=ApiResponse[float])
async def get_balance(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取余额"""
    wallet = get_or_create_wallet(db, current_user.id)
    return ApiResponse(data=wallet.balance)

